{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "f09fd305",
   "metadata": {},
   "source": [
    "# Code writing\n",
    "\n",
    "Example of how to use LCEL to write Python code."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "bd7c259a",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.chat_models import ChatOpenAI\n",
    "from langchain.prompts import (\n",
    "    ChatPromptTemplate,\n",
    ")\n",
    "from langchain_core.output_parsers import StrOutputParser\n",
    "from langchain_experimental.utilities import PythonREPL"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "73795d2d",
   "metadata": {},
   "outputs": [],
   "source": [
    "template = \"\"\"Write some python code to solve the user's problem. \n",
    "\n",
    "Return only python code in Markdown format, e.g.:\n",
    "\n",
    "```python\n",
    "....\n",
    "```\"\"\"\n",
    "prompt = ChatPromptTemplate.from_messages([(\"system\", template), (\"human\", \"{input}\")])\n",
    "\n",
    "model = ChatOpenAI()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "42859e8a",
   "metadata": {},
   "outputs": [],
   "source": [
    "def _sanitize_output(text: str):\n",
    "    _, after = text.split(\"```python\")\n",
    "    return after.split(\"```\")[0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "5ded1a86",
   "metadata": {},
   "outputs": [],
   "source": [
    "chain = prompt | model | StrOutputParser() | _sanitize_output | PythonREPL().run"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "208c2b75",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Python REPL can execute arbitrary code. Use with caution.\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'4\\n'"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "chain.invoke({\"input\": \"whats 2 plus 2\"})"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
